<template>
  <view class="container page-container">
    <!-- 用户信息区域 -->
    <view class="user-info">
      <!-- 已登录状态 -->
      <template v-if="isLogin">
        <view class="logged-in-info">
          <view class="user-main">
            <image class="avatar" :src="userInfo.photo" mode="aspectFill" />
            <view class="user-text">
              <text class="nickname">{{ userInfo.nickname }}</text>
              <text v-if="userInfo.tel" class="tel">{{ userInfo.tel }}</text>
            </view>
          </view>
          <button class="edit-btn" @click="handleEdit">修改信息</button>
        </view>
      </template>
      <!-- 未登录状态 -->
      <template v-else>
        <view class="not-login" @tap="handleUserClick">
          <view class="login-content">
            <image class="default-avatar" src="../../static/default-avatar.jpeg" mode="aspectFill" />
            <view class="login-tip">
              <text class="welcome">欢迎使用</text>
              <text class="login-text">点击登录</text>
            </view>
          </view>
          <uni-icons type="right" size="16" color="#999999" />
        </view>
      </template>
    </view>

    <!-- 登录授权弹窗 -->
    <uni-popup ref="loginPopup" type="bottom">
      <view class="login-popup">
        <view class="popup-header">
          <text class="popup-title">登录授权</text>
          <text class="popup-desc">请选择头像并设置昵称</text>
        </view>

        <!-- 头像选择区域 -->
        <view class="avatar-section">
          <image 
            :src="tempAvatar || '../../static/default-avatar.jpeg'" 
            class="avatar-preview" 
            mode="aspectFill"
          />
          <button class="choose-avatar-btn" open-type="chooseAvatar" @chooseavatar="getAvatar">选择头像</button>
        </view>

        <!-- 昵称输入区域 -->
        <view class="nickname-section">
          <input 
            type="nickname"
            class="nickname-input"
            @input="getNickname"
            @change="getNickname"
            @blur="getNickname"
            :value="tempNickname"
            placeholder="请输入昵称"
          />
        </view>

        <!-- 按钮区域 -->
        <view class="popup-buttons">
          <button class="cancel-btn" @click="handleCancel">取消</button>
          <button 
            class="confirm-btn" 
            :disabled="!tempAvatar || !tempNickname"
            @click="handleLogin"
          >允许</button>
        </view>
      </view>
    </uni-popup>

    <!-- 编辑信息弹窗 -->
    <uni-popup ref="editPopup" type="center">
      <view class="edit-popup">
        <view class="popup-header">
          <text class="popup-title">修改个人信息</text>
        </view>

        <!-- 头像选择区域 -->
        <view class="avatar-section">
          <image 
            :src="tempAvatar || userInfo.photo" 
            class="avatar-preview" 
            mode="aspectFill"
          />
          <button class="choose-avatar-btn" open-type="chooseAvatar" @chooseavatar="getAvatar">更换头像</button>
        </view>

        <!-- 昵称输入区域 -->
        <view class="nickname-section">
          <input 
            type="nickname"
            class="nickname-input"
            @input="getNickname"
            @change="getNickname"
            @blur="getNickname"
            :value="tempNickname || userInfo.nickname"
            placeholder="请输入昵称"
          />
        </view>

        <!-- 按钮区域 -->
        <view class="popup-buttons">
          <button class="cancel-btn" @click="handleEditCancel">取消</button>
          <button 
            class="confirm-btn" 
            @click="handleEditConfirm"
          >确认</button>
        </view>
      </view>
    </uni-popup>

    <!-- 功能列表 -->
    <view class="function-list">
      <view 
        v-for="(item, index) in functionItems" 
        :key="index"
        class="function-item"
        @click="handleItemClick(item)"
      >
        <uni-icons :type="item.icon" size="24" color="#3A86FF" />
        <text class="title">{{ item.title }}</text>
        <text v-if="item.desc" class="desc">{{ item.desc }}</text>
      </view>
    </view>

    <!-- 设置列表 -->
    <view class="setting-list">
      <view 
        v-for="(item, index) in settingItems" 
        :key="index"
        class="setting-item"
        @click="handleItemClick(item)"
      >
        <uni-icons :type="item.icon" size="24" color="#666666" />
        <text class="title">{{ item.title }}</text>
        <uni-icons type="right" size="16" color="#999999" />
      </view>
    </view>

    <!-- 添加待完成预约数量的响应式变量 -->
    <view class="menu-item" @tap="navigateTo('/pages/appointment/appointment')">
      <view class="menu-item-left">
        <uni-icons type="calendar" size="20" color="#2979ff" />
        <text class="menu-item-text">我的预约</text>
      </view>
      <view class="menu-item-right" @tap.stop="navigateTo('/pages/appointment/appointment')">
        <text class="menu-item-desc">待完成预约 {{ appointmentCount }} 个</text>
        <uni-icons type="right" size="16" color="#999999" />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { apiBaseUrl, minioBaseUrl } from '../../config/api'
const baseUrl = `${apiBaseUrl}/patient/user`;

// 登录状态
const isLogin = ref(false);
const userInfo = ref({
  avatar: '/static/images/avatar.png',
  name: '张三',
  phone: '138****8888',
  idCard: '330****8888'
});

// 添加待完成预约数量的响应式变量
const appointmentCount = ref(0)

// 获取待完成预约数量
const getAppointmentCount = async () => {
  try {
    const [err, res] = await uni.request({
      url: `${baseUrl}/selectAppointmentCount`,
      method: 'GET'
    }).then(res => [null, res]).catch(err => [err, null]);

    if (err) {
      throw new Error('网络请求失败');
    }

    const { code, result } = res.data;
    if (code === 200) {
      appointmentCount.value = result;
    }
  } catch (error) {
    console.error('获取待完成预约数量失败:', error);
  }
}

// 页面跳转方法
const navigateTo = (url) => {
  // 判断是否是 tabbar 页面
  if (url === '/pages/appointment/appointment') {
    uni.switchTab({
      url: url
    })
  } else {
    uni.navigateTo({
      url: url
    })
  }
}

// 处理退出登录
const handleLogout = () => {
  // 清除所有存储
  uni.removeStorageSync('token');
  uni.removeStorageSync('userInfo');
  uni.removeStorageSync('id');

  // 重置状态
  isLogin.value = false;
  userInfo.value = {};
  
  // 不需要刷新页面，直接修改状态即可
  console.log('已清除登录状态');
};

// 初始化函数
const initUserInfo = () => {
  const token = uni.getStorageSync('token');
  const storedUserInfo = uni.getStorageSync('userInfo');
  
  console.log('当前token:', token);
  console.log('存储的用户信息:', storedUserInfo);
  
  // 只有当 token 和用户信息都存在时才认为是登录状态
  if (token && storedUserInfo) {
    try {
      const parsedUserInfo = JSON.parse(storedUserInfo);
      // 确保解析后的用户信息包含必要字段
      if (parsedUserInfo && parsedUserInfo.photo && parsedUserInfo.nickname) {
        isLogin.value = true;
        userInfo.value = parsedUserInfo;
      } else {
        // 用户信息不完整，清除所有存储
        console.warn('用户信息不完整，清除登录状态');
        handleLogout();
      }
    } catch (e) {
      console.error('解析用户信息失败:', e);
      // 解析失败时清除所有存储
      handleLogout();
    }
  } else {
    // token 或用户信息任一不存在，都清除所有存储
    console.warn('token或用户信息不存在，清除登录状态');
    handleLogout();
  }
  
  console.log('初始化完成 - 登录状态:', isLogin.value);
  console.log('初始化完成 - 用户信息:', userInfo.value);
};

// 页面加载时初始化
onMounted(() => {
  console.log('页面加载 - 开始初始化');
  initUserInfo();
  getAppointmentCount();
});

// 临时存储登录信息
const tempAvatar = ref('');
const tempNickname = ref('');
const loginPopup = ref(null);

// 功能列表数据
const functionItems = ref([
  { 
    title: '', 
    icon: '', 
    desc: '' 
  },
  { 
    title: '服药提醒', 
    icon: 'notification', 
    desc: '' 
  }
]);

// 设置列表数据
const settingItems = ref([
  { 
    title: '账号安全', 
    icon: 'locked' 
  },
  { 
    title: '隐私设置', 
    icon: 'eye' 
  },
  { 
    title: '关于我们', 
    icon: 'info' 
  }
]);

// 点击用户信息区域
const handleUserClick = () => {
  const platform = uni.getSystemInfoSync().platform;
  console.log(`点击登录区域 - ${platform === 'devtools' ? '开发工具' : '真机'}`);
  
  // 添加延时确保在真机上能正常触发
  setTimeout(() => {
    if (!isLogin.value && loginPopup.value) {
      loginPopup.value.open();
    }
  }, 100);
};

// 获取头像
const getAvatar = (e) => {
  console.log('获取到的头像路径:', e.detail.avatarUrl);
  tempAvatar.value = e.detail.avatarUrl;
};

// 获取昵称
const getNickname = (e) => {
  console.log('昵称输入事件触发:', e);
  // 优先使用 detail.value，如果没有则使用 target.value
  const nickname = e.detail.value || e.target.value;
  if (nickname) {
    tempNickname.value = nickname;
    console.log('设置的昵称:', tempNickname.value);
  }
};

// 取消登录
const handleCancel = () => {
  loginPopup.value.close();
  // 清空临时数据
  tempAvatar.value = '';
  tempNickname.value = '';
};

// 确认登录
const handleLogin = async () => {
  if (!tempAvatar.value || !tempNickname.value) {
    uni.showToast({
      title: '请完善个人信息',
      icon: 'none'
    });
    return;
  }

  try {
    // 显示加载提示
    uni.showLoading({
      title: '登录中...'
    });

    // 清理旧的登录信息
    uni.removeStorageSync('token');
    uni.removeStorageSync('userInfo');
    uni.removeStorageSync('id');

    // 1. 获取临时授权码
    const loginResult = await uni.login({
      provider: 'weixin',
      // 强制重新登录
      force: true
    });
    
    if (!loginResult.code) {
      throw new Error('获取授权码失败');
    }

    console.log('登录环境:', uni.getSystemInfoSync().platform);
    console.log('获取到的临时授权码:', loginResult.code);

    // 开发环境下的提示
    if (uni.getSystemInfoSync().platform === 'devtools') {
      console.warn('在开发工具中测试时：');
      console.warn('1. 请保持"不校验合法域名"选项勾选');
      console.warn('2. 请取消勾选"将 AppSecret 配置到本地"');
      console.warn('3. 如果 code 依然相同，请点击开发者工具的"清缓存"按钮后重试');
    }

    // 2. 上传头像
    const uploadRes = await uni.uploadFile({
      url: `${baseUrl}/uploadAvatar`,
      filePath: tempAvatar.value,
      name: 'file',
      header: {
        'Accept': '*/*',
        'Content-Type': 'multipart/form-data'
      }
    });

    const uploadData = JSON.parse(uploadRes.data);
    if (uploadData.code !== 200) {
      throw new Error(uploadData.message || '头像上传失败');
    }

    // 3. 发起登录请求
    const loginRes = await uni.request({
      url: `${baseUrl}/loginOrRegister`,
      method: 'POST',
      data: {
        code: loginResult.code,
        photo: uploadData.result,
        nickname: tempNickname.value,
        sex: '男'
      }
    });

    if (loginRes.data.code === 200) {

      console.log('----------------------------------------');
      console.log(loginRes);
      console.log('----------------------------------------');
      // 保存用户信息到本地存储
      const userInfoData = {
        photo: uploadData.result,
        nickname: tempNickname.value,
        tel: loginRes.data.tel || ''
      };
      
      uni.setStorageSync('token', loginRes.data.token);
      uni.setStorageSync('userInfo', JSON.stringify(userInfoData));
      uni.setStorageSync('id', loginRes.data.id);
      uni.setStorageSync('openId', loginRes.data.openId);
      
      // 更新状态
      isLogin.value = true;
      userInfo.value = userInfoData;

      // 关闭弹窗
      loginPopup.value.close();
      
      uni.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 1500
      });
    } else {
      throw new Error(loginRes.data.message || '登录失败');
    }
  } catch (error) {
    console.error('登录失败:', error);
    uni.showToast({
      title: error.message || '登录失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 列表项点击事件处理
const handleItemClick = (item) => {
  switch (item.title) {
    case '账号安全':
      uni.navigateTo({
        url: '/pages/user/account-security/account-security'
      })
      break
    case '隐私设置':
      uni.navigateTo({
        url: '/pages/user/privacy-settings/privacy-settings'
      })
      break
    case '关于我们':
      uni.navigateTo({
        url: '/pages/user/about/about'
      })
      break
    default:
      uni.showToast({
        title: '功能开发中',
        icon: 'none'
      })
  }
}

/**
 * 
 * *******************************修改信息逻辑
 * 
 */

const editPopup = ref(null);
const id = ref('');

// 点击修改信息
const handleEdit = () => {
  // 清空临时数据
  tempAvatar.value = '';
  tempNickname.value = '';
  // 打开编辑弹窗
  editPopup.value.open();
};

// 取消编辑
const handleEditCancel = () => {
  editPopup.value.close();
  // 清空临时数据
  tempAvatar.value = '';
  tempNickname.value = '';
};

// 确认编辑
const handleEditConfirm = async () => {
  id.value = uni.getStorageSync('id');

  try {
    uni.showLoading({
      title: '保存中...'
    });

    let newAvatarUrl = userInfo.value.photo;

    // 如果选择了新头像，先上传
    if (tempAvatar.value) {
      const uploadRes = await uni.uploadFile({
        url: `${baseUrl}/uploadAvatar`,
        filePath: tempAvatar.value,
        name: 'file',
        header: {
          'Accept': '*/*',
          'Content-Type': 'multipart/form-data'
        }
      });

      const uploadData = JSON.parse(uploadRes.data);
      if (uploadData.code !== 200) {
        throw new Error(uploadData.message || '头像上传失败');
      }
      newAvatarUrl = uploadData.result;
    }

    // 发送更新请求
    const updateRes = await uni.request({
      url: `${baseUrl}/update`,
      method: 'POST',
      data: {
        id: id.value,
        photo: newAvatarUrl,
        nickname: tempNickname.value || userInfo.value.nickname
      }
    });

    if (updateRes.data.code === 200) {
      // 更新本地存储的用户信息
      const newUserInfo = {
        ...userInfo.value,
        photo: newAvatarUrl,
        nickname: tempNickname.value || userInfo.value.nickname
      };
      uni.setStorageSync('userInfo', JSON.stringify(newUserInfo));

      // 更新当前显示的用户信息
      userInfo.value = newUserInfo;

      // 关闭弹窗
      editPopup.value.close();
      
      uni.showToast({
        title: '修改成功',
        icon: 'success'
      });

      // 清空临时数据
      tempAvatar.value = '';
      tempNickname.value = '';
    } else {
      throw new Error(updateRes.data.message || '修改失败');
    }
  } catch (error) {
    uni.showToast({
      title: error.message || '修改失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};
</script>

<style lang="scss">
.page-container {
  padding-top: 65px; /* 增加padding-top，使内容位于胶囊按钮下方 */
  min-height: 100vh;
  background-color: #f5f5f5;
  box-sizing: border-box;
}

.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.user-info {
  background-color: #ffffff;
  padding: 40rpx;
  margin-top: 20rpx;
  
  .logged-in-info {
    position: relative;
    padding: 20rpx 0;
    
    .user-main {
      display: flex;
      align-items: center;
    }
    
    .avatar {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      margin-right: 30rpx;
    }
    
    .user-text {
      display: flex;
      flex-direction: column;
      justify-content: center;
      
      .nickname {
        font-size: 32rpx;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .tel {
        font-size: 28rpx;
        color: #666;
      }
    }
    
    .edit-btn {
      position: absolute;
      right: 0;
      bottom: 0;
      font-size: 24rpx;
      color: #3A86FF;
      background: none;
      padding: 10rpx 20rpx;
      border: 1px solid #3A86FF;
      border-radius: 30rpx;
      line-height: 1.5;
      
      &::after {
        border: none;
      }
      
      &:active {
        opacity: 0.8;
      }
    }
  }
  
  .not-login {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 0;
    
    .login-content {
      display: flex;
      align-items: center;
      flex: 1;
    }
    
    .default-avatar {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      margin-right: 30rpx;
      background-color: #f5f5f5;
    }
    
    .login-tip {
      display: flex;
      flex-direction: column;
      
      .welcome {
        font-size: 32rpx;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .login-text {
        font-size: 28rpx;
        color: #3A86FF;
      }
    }
  }
}

.login-popup {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 40rpx;
  
  .popup-header {
    text-align: center;
    margin-bottom: 40rpx;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
      display: block;
    }
    
    .popup-desc {
      font-size: 28rpx;
      color: #666;
    }
  }
  
  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 40rpx;
    
    .avatar-preview {
      width: 160rpx;
      height: 160rpx;
      border-radius: 50%;
      margin-bottom: 20rpx;
    }
    
    .choose-avatar-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      background-color: #f5f5f5;
      border-radius: 12rpx;
      font-size: 28rpx;
      color: #333;
      text-align: left;
      padding: 0 24rpx;
      
      &::after {
        border: none;
      }
    }
  }
  
  .nickname-section {
    margin-bottom: 40rpx;
    
    .nickname-input {
      width: 100%;
      height: 88rpx;
      background-color: #f5f5f5;
      border-radius: 12rpx;
      padding: 0 24rpx;
      font-size: 28rpx;
    }
  }
  
  .popup-buttons {
    display: flex;
    gap: 20rpx;
    
    .cancel-btn, .confirm-btn {
      flex: 1;
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 44rpx;
      font-size: 32rpx;
    }
    
    .cancel-btn {
      background-color: #f5f5f5;
      color: #666;
    }
    
    .confirm-btn {
      background-color: #07c160;
      color: #fff;
      
      &[disabled] {
        background-color: #ccc;
      }
    }
  }
}

.edit-popup {
  background-color: #fff;
  border-radius: 24rpx;
  padding: 40rpx;
  width: 600rpx;
  
  .popup-header {
    text-align: center;
    margin-bottom: 40rpx;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 40rpx;
    
    .avatar-preview {
      width: 160rpx;
      height: 160rpx;
      border-radius: 50%;
      margin-bottom: 20rpx;
    }
    
    .choose-avatar-btn {
      font-size: 28rpx;
      color: #3A86FF;
      background: none;
      padding: 10rpx 30rpx;
      border: 1px solid #3A86FF;
      border-radius: 30rpx;
      
      &::after {
        border: none;
      }
    }
  }
  
  .nickname-section {
    margin-bottom: 40rpx;
    
    .nickname-input {
      width: 100%;
      height: 88rpx;
      background-color: #f5f5f5;
      border-radius: 12rpx;
      padding: 0 24rpx;
      font-size: 28rpx;
    }
  }
  
  .popup-buttons {
    display: flex;
    gap: 20rpx;
    
    .cancel-btn, .confirm-btn {
      flex: 1;
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 44rpx;
      font-size: 32rpx;
    }
    
    .cancel-btn {
      background-color: #f5f5f5;
      color: #666;
    }
    
    .confirm-btn {
      background-color: #07c160;
      color: #fff;
      
      &:active {
        opacity: 0.8;
      }
    }
  }
}

.function-list {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  
  .function-item {
    display: flex;
    align-items: center;
    padding: 30rpx 20rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .title {
      font-size: 30rpx;
      margin-left: 20rpx;
      flex: 1;
    }
    
    .desc {
      font-size: 26rpx;
      color: #999999;
    }
  }
}

.setting-list {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
  
  .setting-item {
    display: flex;
    align-items: center;
    padding: 30rpx 20rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .title {
      font-size: 30rpx;
      margin-left: 20rpx;
      flex: 1;
    }
  }
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }
  
  .menu-item-left {
    display: flex;
    align-items: center;
  }
  
  .menu-item-text {
    font-size: 30rpx;
    margin-left: 20rpx;
  }
  
  .menu-item-right {
    display: flex;
    align-items: center;
  }
  
  .menu-item-desc {
    font-size: 26rpx;
    color: #999999;
  }
}
</style>
